package com.xxx.car.web.admin;

import com.github.pagehelper.PageInfo;
import com.xxx.car.entity.TbBanner;
import com.xxx.car.entity.vo.request.ReqBannerAdminQuery;
import com.xxx.car.entity.vo.request.ReqUserCarAdminQuery;
import com.xxx.car.service.BannerService;
import com.xxx.car.service.CommonService;
import com.xxx.common.base.enums.AdminErrorEnum;
import com.xxx.common.base.enums.ApiResponseEnum;
import com.xxx.common.base.vo.APIResponse;
import com.xxx.common.base.vo.AdminResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;

/**
 * Created by youxiaojia on 2017/6/19.
 */
@Controller
@RequestMapping("/admin/banner")
public class AdminBannerController {

    @Value("${upload.filePath}")
    private String filePath;

    @Autowired
    ResourceLoader resourceLoader;

    @Autowired
    CommonService commonService;
    @Autowired
    BannerService bannerService;

    @RequestMapping(value = "/")
    public String bannerList(Model model, @ModelAttribute ReqBannerAdminQuery query) {
        PageInfo pageInfo = bannerService.queryBannerListByAdmin(query);
        //获得当前页
        model.addAttribute("pageNum", pageInfo.getPageNum());
        //获得一页显示的条数
        model.addAttribute("pageSize", pageInfo.getPageSize());
        //是否是第一页
        model.addAttribute("isFirstPage", pageInfo.isIsFirstPage());
        //获得总页数
        model.addAttribute("totalPages", pageInfo.getPages());
        //是否是最后一页
        model.addAttribute("isLastPage", pageInfo.isIsLastPage());
        model.addAttribute("bannerList",pageInfo.getList());
        return "bannerList";
    }

    @RequestMapping(value = "/add")
    public String bannerAdd(Model model){
        return "bannerAdd";
    }

    @RequestMapping(value = "/update")
    public String bannerUpdate(Model model,@RequestParam("id") Integer id){
        System.out.println(id);
        TbBanner tbBanner = bannerService.queryBannerDetailById(id);
        model.addAttribute("banner",tbBanner);
        return "bannerUpdate";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/addBanner")
    public String addBanner(@RequestParam("bannerFile") MultipartFile bannerFile, @RequestParam("editorContent") String editorContent,Model model,HttpServletRequest request)
            throws IOException {

        if (bannerFile.isEmpty()) {
            model.addAttribute("response", APIResponse.returnFail("请选择文件"));
        }
        String newFileName = null;
        try {
            newFileName = commonService.uploadFile(bannerFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (newFileName != null && editorContent != null && editorContent != ""){
            TbBanner tbBanner = new TbBanner();
            tbBanner.setPicName(newFileName);
            tbBanner.setContent(editorContent);
            APIResponse response = bannerService.addBanner(tbBanner);
            model.addAttribute("response", response);
        }
        return "redirect:/admin/banner/";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/updateBanner")
    public String updateBanner(@RequestParam("bannerFile") MultipartFile bannerFile,@RequestParam("id") String id, @RequestParam("editorContent") String editorContent,Model model,HttpServletRequest request)
            throws IOException {
        Integer bannerId = Integer.parseInt(id);
        if (bannerFile.isEmpty()) {
            model.addAttribute("response", APIResponse.returnFail("请选择文件"));
        }
        String newFileName = null;
        try {
            newFileName = commonService.uploadFile(bannerFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (newFileName != null && editorContent != null && editorContent != ""){
            TbBanner tbBanner = new TbBanner();
            tbBanner.setId(bannerId);
            tbBanner.setPicName(newFileName);
            tbBanner.setContent(editorContent);
            APIResponse response = bannerService.updateBanner(tbBanner);
            model.addAttribute("response", response);
        }
        return "redirect:/admin/banner/";
    }

    /**
     * editor 图片上传
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/editorPicUpload")
    public @ResponseBody String uploadImageByEditor(@RequestParam("filedata") MultipartFile file, HttpServletRequest request) throws IOException {
        String message = "";
        String err = "";
        String msg = "/admin/banner/pics/";
        if (!file.isEmpty()) {
            try {
                String fileName = commonService.uploadFile(file);
                msg = msg + fileName;
                message = "{\"err\":\"" + err + "\",\"msg\":\"" + msg
                        + "\"}";
                err = message;
                return message;
            } catch (Exception e) {
                e.printStackTrace();
                return message;
            }
        } else {
            return message;
        }
    }

    /**
     * editor 图片回显
     * @param filename
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/pics/{filename:.+}")
    @ResponseBody
    public ResponseEntity<?> getFile(@PathVariable String filename) {

        try {
            return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(filePath, filename).toString()));
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }

}
